package com.shopping.mall.core.module.type.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.mall.core.module.type.entity.Type;
import com.shopping.mall.core.module.type.entity.TypeIds;
import com.shopping.mall.core.module.type.entity.TypeLan;
import com.shopping.mall.core.module.type.mapper.TypeLanMapper;
import com.shopping.mall.core.module.type.mapper.TypeMapper;
import com.shopping.mall.core.module.type.service.TypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.base.util.WrapperUtils;
import com.shopping.mall.core.util.LanguageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * Type服务实现类
 * </p>
 *
 * @author zzy
 * @since 2021-08-11
 */
@Validated
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private TypeLanMapper typeLanMapper;

    /**
     * 分页查询
     *
     * @param current：页码
     * @param size：每页条数
     * @param type：筛选条件
     * @return IPage<Type>
     */
    @Override
    public IPage<Type> getTypePage(Integer current, Integer size, Type type) {
        QueryWrapper<Type> queryWrapper = WrapperUtils.queryWrapper(type);
        queryWrapper.orderByAsc("order_num");
        Page<Type> typePage = new Page<>(current, size);
        return typeMapper.selectPage(typePage, queryWrapper);
    }

    /**
     * 查询所有
     *
     * @param type：筛选条件
     * @return List<Type>
     */
    @Override
    public List<Type> getAll(Type type) {
        String languageId = LanguageUtil.getLanguageId();
        if (languageId == null) {
            QueryWrapper<Type> queryWrapper = WrapperUtils.queryWrapper(type);
            return typeMapper.selectList(queryWrapper);
        } else {
            QueryWrapper<TypeLan> typeLanQueryWrapper = WrapperUtils.queryWrapper(type.getTypeLan());
            List<TypeLan> typeLanList = typeLanMapper.selectList(typeLanQueryWrapper);
            List<Type> typeList = new ArrayList<>();
            List<String> typeLanIds = new ArrayList<>();
            for (TypeLan typeLan : typeLanList) {
                typeLanIds.add(typeLan.getTypeId());
                typeList.add(typeLan.getType());
            }
            QueryWrapper<Type> typeQueryWrapper = WrapperUtils.queryWrapper(type);
            typeQueryWrapper.notIn("id", typeLanIds);
            typeQueryWrapper.orderByAsc("order_num");
            typeList.addAll(typeMapper.selectList(typeQueryWrapper));
            return typeList;
        }

    }

    /**
     * 通过id删除
     *
     * @param id：typeId
     * @return Result<Object>
     */
    @Override
    @Transactional
    public Result<Object> deleteById(String id) {
        Type type = typeMapper.selectById(id);
        if (type == null) {
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        List<Type> children = typeMapper.selectList(WrapperUtils.getQueryWrapper("parent_id", type.getId()));
        if (children != null && children.size() > 0) {
            return Result.error(ResponseState.HAS_CHILDREN.getValue(), ResponseState.HAS_CHILDREN.getMessage());
        }
        typeMapper.deleteById(id);
        typeLanMapper.delete(WrapperUtils.getUpdateWrapper("type_id", type.getId()));
        return Result.OK();
    }

    /**
     * 批量删除
     *
     * @param ids：id列表
     * @return Result<Object>
     */
    @Override
    @Transactional
    public Result<Object> batchDelete(List<String> ids) {
        UpdateWrapper<Type> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", ids);
        typeMapper.delete(updateWrapper);
        UpdateWrapper<TypeLan> typeLanUpdateWrapper = new UpdateWrapper<>();
        typeLanUpdateWrapper.in("type_id", ids);
        typeLanMapper.delete(typeLanUpdateWrapper);
        return Result.OK();
    }

    /**
     * 新增
     *
     * @param type ：类型
     * @return Result<Object>
     */
    @Override
    public Result<Object> add(Type type) {
        if (type.getParentId() != null) {
            Type parentType = typeMapper.selectById(type.getParentId());
            if (parentType == null) {
                return Result.error(ResponseState.PARENT_NOT_EXIST.getValue(), ResponseState.PARENT_NOT_EXIST.getMessage());
            }
            type.setLevel(parentType.getLevel()+1);
            type.setOrderNum(typeMapper.selectOrderNumByParent(type.getParentId())+1);
        }else {
            type.setLevel(1);
            type.setOrderNum(typeMapper.selectRootOrderNum()+1);
        }
        typeMapper.insert(type);
        return Result.OK();
    }

    /**
     * 树型结构查询所有
     *
     * @return Result<List < Type>>
     */
    @Override
    public Result<List<Type>> getTree() {
        String languageId = LanguageUtil.getLanguageId();
        //获取所有节点
        List<Type> typeList = new ArrayList<>();
        if (languageId != null) {
            //查询有翻译的
            List<TypeLan> typeLanList = typeLanMapper.selectList(WrapperUtils.getQueryWrapper("language_id", languageId));
            List<String> typeLanListId = new ArrayList<>();
            for (TypeLan typeLan : typeLanList) {
                typeList.add(typeLan.getType());
                typeLanListId.add(typeLan.getTypeId());
            }
            //查询没有翻译的
            QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();
            typeQueryWrapper.notIn("id", typeLanListId);
            typeQueryWrapper.orderByAsc("order_num");
            typeList.addAll(typeMapper.selectList(typeQueryWrapper));
        } else {
            QueryWrapper<Type> queryWrapper=new QueryWrapper<>();
            queryWrapper.orderByAsc("order_num");
            typeList = typeMapper.selectList(queryWrapper);
        }
        List<Type> typeRoot = new ArrayList<>();
        Map<String, List<Type>> children = new HashMap<>();
        for (Type type : typeList) {
            //查询根节点
            if (type.getLevel() == 1) {
                typeRoot.add(type);
                //将同一类子节点放入同一list里
            } else {
                if (children.get(type.getParentId()) != null) {
                    children.get(type.getParentId()).add(type);
                } else {
                    List<Type> childrenNode = new ArrayList<>();
                    childrenNode.add(type);
                    children.put(type.getParentId(), childrenNode);
                }
            }
        }
        //分配子节点
        for (Type type : typeRoot) {
            type.setChildren(children.get(type.getId()));
            if (type.getChildren() != null) {
                for (Type typeChildren : type.getChildren()) {
                    typeChildren.setChildren(children.get(typeChildren.getId()));
                }
            }
        }
        return Result.OK(typeRoot);
    }

    /**
     * 排序
     */
    @Override
    public void order(TypeIds ids) {
        int i=1;
        if(ids!=null&&ids.getIds()!=null&&ids.getIds().size()>0){
            for(String id:ids.getIds()){
                typeMapper.updateById(new Type(id,i));
                i++;
            }
        }
    }


}